/**
 * Created by zhangxiaoyu on 16/12/12.
 */
angular.module('hyt.abnormalCtrl',[])

  .controller('abnormalListCtrl',function($scope,AbnormalList,Storage,$state){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var userMsg={
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    AbnormalList.getAbnormalData(userMsg);
    $scope.$on('AbnormalList.Updated', function() {
      $scope.abnormalData=AbnormalList.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      AbnormalList.getAbnormalData(userMsg);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      AbnormalList.getMoreAbnormalData(userMsg);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return AbnormalList.hasNextPage();
    };
    $scope.goAbnormalDetail=function (data,id) {
      Storage.set('abnormalDetail',data);
      $state.go('abnormalDetail',{id:id});
    }
  })
  .controller('abnormalDetailCtrl',function($scope,Storage,$stateParams,DownLoadAbnormalImg){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var downLoadImg={
      wayBillId:$stateParams.id,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    DownLoadAbnormalImg.getDownLoadImg(JSON.stringify(downLoadImg));
    $scope.$on('DownLoadAbnormalImg.Updated', function() {
      var result=DownLoadAbnormalImg.getResult();
      $scope.imgData=result.rows;
      $scope.showloading=false;
    });
    //点击图片放大
    $scope.showBigImage = function (imageName) {  //传递一个参数（图片的URl）
      $scope.Url = imageName;                   //$scope定义一个变量Url，这里会在大图出现后再次点击隐藏大图使用
      $('.tabs').removeClass("show").addClass("hide");
      $('#bigImg').show(500);
    };
    $scope.hideBigImage = function () {
      $('#bigImg').hide(500);
      $('.tabs').removeClass("hide").addClass("show");
    };
    $scope.abnormalDetail=Storage.get('abnormalDetail');
    switch ($scope.abnormalDetail.ABNORMAL_STATUS){
      case '0' :
        $scope.ABNORMAL_STATUS = '待处理';
        break;
      case '1' :
        $scope.ABNORMAL_STATUS = '待审核';
        break;
      case '2' :
        $scope.ABNORMAL_STATUS = '未通过';
        break;
      case '3' :
        $scope.ABNORMAL_STATUS = '已通过';
        break;
      default :
        break;
    }
    switch ($scope.abnormalDetail.CARGO_TYPE){
      case '0' :
        $scope.CARGO_TYPE = '货多';
        break;
      case '1' :
        $scope.CARGO_TYPE = '货少';
        break;
      case '2' :
        $scope.CARGO_TYPE = '货损';
        break;
      case '3' :
        $scope.CARGO_TYPE = '货少且货损';
        break;
      default :
        break;
    }
  })
  .controller('searchListCtrl',function($scope,Storage,SearchWb,$cordovaBarcodeScanner){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    $scope.search={
      wayBillNo:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    $scope.$on('$ionicView.enter', function() {
      if ($scope.search.wayBillNo==''){
        $("#searchWb").focus();
      }
    });
    document.onkeydown=function(event){
      if(event.keyCode==13&&$scope.search.wayBillNo!=''){
        SearchWb.getWbList(JSON.stringify($scope.search));
      }
    };
    $scope.qrScanner=function(){
      document.addEventListener("deviceready", function () {

        $cordovaBarcodeScanner
          .scan()
          .then(function(barcodeData) {
            $scope.search.wayBillNo=barcodeData.text;
            SearchWb.getWbList(JSON.stringify($scope.search));
          }, function(error) {
            // An error occurred
          });
      }, false);
    };
    $scope.$on('SearchWb.Updated', function() {
      $scope.searchResult=SearchWb.getResult();
      $scope.showloading=false;
    });
  })
  .controller('reportAbnlCtrl',function($scope,Storage,$stateParams,SaveAbnormal,$ionicLoading,$state,$ionicActionSheet,$cordovaImagePicker,$cordovaCamera,$ionicPopup,UploadAbnormaImg){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.waybillNo=$stateParams.WAYBILL_NO;
    $scope.cargoType={
      goodsMore:'',
      goodsDamage:'',
      goodsLess:''
    };
    $scope.cargoNumber={
      moreNum:'',
      damageNum:'',
      lessNum:''
    };
    $scope.reportAbnl={
      abnormalInfo:{
        waybillId:$stateParams.WAYBILL_ID,
        cargoLinks:$stateParams.WAYBILL_STATUS,
        companyId:userMsg.rows.baseDeptId,
        liableName:userMsg.rows.username,
        remark:''
      },
      lose:[],
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    var upImg={
      wayBillId:$stateParams.WAYBILL_ID,
      fileName:'',
      fileContext:''
    };
    $scope.selectTypeM=function(){
      if($scope.cargoType.goodsMore==true){
        $('#goodsMore').removeClass("hide").addClass("show");
        $scope.cargoType.goodsLess=false;
        $('#goodsLess').removeClass("show").addClass("hide");
        $scope.reportAbnl.lose.push({cargoType:'0',cargoNumber:''});
        $.each($scope.reportAbnl.lose,function(i,item){
          if(item.cargoType=='1'){
            $scope.reportAbnl.lose.splice(i,1);
          }
        });
      }else {
        $('#goodsMore').removeClass("show").addClass("hide");
        $.each($scope.reportAbnl.lose,function(i,item){
          if(item.cargoType=='0'){
            $scope.reportAbnl.lose.splice(i,1);
          }
        });
      }
    };
    $scope.selectTypeD=function(){
      if($scope.cargoType.goodsDamage==true){
        $('#goodsDamage').removeClass("hide").addClass("show");
        $scope.reportAbnl.lose.push({cargoType:'2',cargoNumber:''});
      }else {
        $('#goodsDamage').removeClass("show").addClass("hide");
        $.each($scope.reportAbnl.lose,function(i,item){
          if(item.cargoType=='2'){
            $scope.reportAbnl.lose.splice(i,1);
          }
        });
      }
    };
    $scope.selectTypeL=function(){
      if($scope.cargoType.goodsLess==true){
        $('#goodsLess').removeClass("hide").addClass("show");
        $scope.cargoType.goodsMore=false;
        $('#goodsMore').removeClass("show").addClass("hide");
        $scope.reportAbnl.lose.push({cargoType:'1',cargoNumber:''});
        $.each($scope.reportAbnl.lose,function(i,item){
          if(item.cargoType=='0'){
            $scope.reportAbnl.lose.splice(i,1);
          }
        });
      }else {
        $('#goodsLess').removeClass("show").addClass("hide");
        $.each($scope.reportAbnl.lose,function(i,item){
          if(item.cargoType=='1'){
            $scope.reportAbnl.lose.splice(i,1);
          }
        });
      }
    };
    var imgPic=[];
    $scope.imgData=[];
    $scope.actionSheet=function(){
      var hideSheet = $ionicActionSheet.show({
        buttons: [
          { text: '拍照' },
          { text: '从相册选择' }
        ],
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if(index==0){
            var options = {
              destinationType: Camera.DestinationType.NATIVE_URI,
              sourceType: Camera.PictureSourceType.CAMERA,
              targetWidth: 800,
              targetHeight: 800
            };

            $cordovaCamera.getPicture(options).then(function(imageURI) {
              if (imgPic.length>2){
                $ionicLoading.show({
                  noBackdrop: true,
                  template: "最多支持三张照片",
                  duration: 1500
                });
              }else {
                imgPic[imgPic.length]= imageURI;
              }
            }, function(err) {
              // error
            });
          }else if (index==1){
            var options = {
              maximumImagesCount: 10,
              width: 800,
              height: 800,
              quality: 80
            };

            $cordovaImagePicker.getPictures(options)
              .then(function (results) {
                if (imgPic.length+results.length>3){
                  $ionicLoading.show({
                    noBackdrop: true,
                    template: "最多支持三张照片",
                    duration: 1500
                  });
                }else {
                  for (var i = 0,j=imgPic.length; i < results.length; i++,j++) {
                    imgPic[j]=results[i];
                  }
                }
              }, function(error) {
                // error getting photos
              });
          }
          $scope.imgData=imgPic;

          return true;
        }
      });
    };
    $scope.deleteImg=function(img){
      var j;
      var receipt = $ionicPopup.confirm({
        title : '是否删除图片',
        cancelText : '否',
        cancelType : 'button-stable',
        okText : '是'
      });
      receipt.then(function(r){
        if(r){
          for (var i=0;i<$scope.imgData.length;i++){
            if ($scope.imgData[i]==img){
              j=i;
              $scope.imgData.splice(j,1);
            }
          }
        }else{
          console.log('取消');
        }
      });
    };
    $scope.saveAbnl=function(){
      $.each($scope.reportAbnl.lose,function(i,item){
        if(item.cargoType=='0'){
          $scope.reportAbnl.lose[i].cargoNumber=$scope.cargoNumber.moreNum;
        }
        if(item.cargoType=='1'){
          $scope.reportAbnl.lose[i].cargoNumber=$scope.cargoNumber.lessNum;
        }
        if(item.cargoType=='2'){
          $scope.reportAbnl.lose[i].cargoNumber=$scope.cargoNumber.damageNum;
        }
      });
      if ($scope.reportAbnl.lose.length==0){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入异常信息",
          duration: 1500
        });
      }else if ($scope.reportAbnl.lose.length==1&&($scope.reportAbnl.lose[0].cargoNumber==''||$scope.reportAbnl.lose[0].cargoNumber==null)){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入异常件数",
          duration: 1500
        });
      }else if ($scope.reportAbnl.lose.length==2&&($scope.reportAbnl.lose[0].cargoNumber==''||$scope.reportAbnl.lose[0].cargoNumber==null||$scope.reportAbnl.lose[1].cargoNumber==''||$scope.reportAbnl.lose[1].cargoNumber==null)){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入异常件数",
          duration: 1500
        });
      }else {
        SaveAbnormal.getSaveAbnl(JSON.stringify($scope.reportAbnl));
      }
      $scope.$on('SaveAbnl.Updated', function() {
        var result=SaveAbnormal.getResult();
        if (result.success==true){
          uploadImg();
          $ionicLoading.show({
            noBackdrop: true,
            template: "上报成功",
            duration: 1500
          });
          $state.go('tab.workbench');
        }
      });
    };
    function uploadImg(){
      for (var i=0;i<$scope.imgData.length;i++){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        var img = new Image();
        img.crossOrigin = 'Anonymous';
        img.src = $scope.imgData[i];
        img.onload = function(){
          canvas.height = this.height;
          canvas.width = this.width;
          ctx.drawImage(this,0,0,this.width,this.height);
          var ext = this.src.substring(this.src.lastIndexOf(".")+1).toLowerCase();
          var extendName = this.src.substring(this.src.lastIndexOf("/")+1).toLowerCase();
          dataURL = canvas.toDataURL("image/"+ext);
          upImg.fileName=extendName;
          upImg.fileContext=dataURL;
          UploadAbnormaImg.getUpImg(upImg);
        };
      }
    }
  });
